package com.jianzhi.lib.log.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.blankj.utilcode.util.NetworkUtils
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ThreadUtils.SimpleTask

class UploadService : Service() {

    private val handler = ServiceHandler(this)

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        handler.sendEmptyMessage(ServiceHandler.WHAT_DO_UPLOAD_LOG)
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    fun doUpload() {
        if (NetworkUtils.isConnected()) {
            handler.removeMessages(ServiceHandler.WHAT_DO_UPLOAD_LOG)
            ThreadUtils.executeByIo(object : SimpleTask<Any>() {
                override fun doInBackground(): Any {
                    // 1）从数据库中拿出最早的记录
                    // 2）上报拿到的记录
                    // 3）删除记录
                    return Any()
                }

                override fun onSuccess(result: Any?) {
                    handler.sendEmptyMessage(ServiceHandler.WHAT_DO_UPLOAD_LOG)
                }

            })
        } else {
            handler.sendEmptyMessageDelayed(ServiceHandler.WHAT_DO_UPLOAD_LOG, 10 * 1000)
        }
    }
}